package it.nola.soccer;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class ConfEdit extends Activity {
    private DbHelper dbHelper;
    private Spinner playerNrSpinner;
    private EditText mailFromText;
    private EditText mailToText;

    private void fillData() {
	Cursor cc=dbHelper.cercaConfig();
	startManagingCursor(cc);
	cc.moveToFirst();
	mailFromText.setText(cc.getString(cc.getColumnIndex(Const.Config.KEY_MAIL_FROM)));
	mailToText.setText(cc.getString(cc.getColumnIndex(Const.Config.KEY_MAIL_TO)));
	playerNrSpinner.setSelection(cc.getInt(cc.getColumnIndex(Const.Config.KEY_DEFAULT_PL_NUMBER)));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setTitle(getText(R.string.preferences));
	setContentView(R.layout.config_edit);
	dbHelper=new DbHelper(this);
	dbHelper.open();
	prepareFields();
	fillData();
    }

    /**
     * Inizializza i campi presenti nella View
     */
    private void prepareFields() {
	mailFromText=(EditText) findViewById(R.id.mail_from);
	mailToText=(EditText) findViewById(R.id.mail_to);
	playerNrSpinner=(Spinner) findViewById(R.id.def_nr_player);
	ArrayAdapter<CharSequence> plNrAdapter=ArrayAdapter.createFromResource(this, R.array.player_numbers,
	    android.R.layout.simple_spinner_item);
	playerNrSpinner.setAdapter(plNrAdapter);
    }

    public void salva(View view) {
	saveState();
	finish();
    }

    private void saveState() {
	long nrPl=playerNrSpinner.getSelectedItemId();
	String mailTo=mailToText.getText().toString();
	String mailFrom=mailFromText.getText().toString();
	dbHelper.updateConfig(nrPl, mailTo, mailFrom);
	Toast toast=Toast.makeText(this, getString(R.string.just_saved), Toast.LENGTH_LONG);
	toast.show();
    }
}
